package cn.wolfcode.wms.service.impl;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.mapper.EmployeeMapper;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.qo.QueryObject;
import cn.wolfcode.wms.service.IEmployeeService;
import cn.wolfcode.wms.util.PageResult;
import cn.wolfcode.wms.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    //登录验证
    public void selectInfo(String username, String password) {
        Employee e =employeeMapper.selectByinfo(username,password);
        if (e == null) {
            throw new RuntimeException("账号或密码错误");
        }
        UserContext.setCurrentUser(e);
        //拿到用户对应权限
        List<String> exps =permissionMapper.selectByEmployeeId(e.getId());
        UserContext.setCurrentPermission(exps);

    }

    @Override
    public void saveOrUpdate(Employee entity, Long[] roleIds) {
        if (entity.getId() != null) {
            employeeMapper.updateByPrimaryKey(entity);
            //删除关系,插入关系
            if (roleIds != null) {
                employeeMapper.deleteRelation(entity.getId());
            }
        } else {
            employeeMapper.insert(entity);
        }
        if (roleIds != null) {
            for (Long permissId : roleIds) {

                employeeMapper.insertRelation(entity.getId(), permissId);
            }
        }
    }
    @Override
    public void delete(Long id) {
        if (id != null) {
            employeeMapper.deleteRelation(id);
            employeeMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public Employee get(Long id) {

            Employee entity = employeeMapper.selectByPrimaryKey(id);
        return entity;

    }

    @Override
    public List<Employee> selectall() {
        List<Employee> depts = employeeMapper.selectAll();
        return depts;
    }

    @Override
    public PageResult queryForList(QueryObject qo) {
        int rows = employeeMapper.rows(qo);
        if (rows == 0) {
            return PageResult.EMPTY_RESULT;
        }
        return new PageResult(qo.getCurrentPage(),qo.getPageSize(),rows,employeeMapper.queryForList(qo));
    }
}
